package com.itlaoqi.rabbitmq.confirm;

import com.itlaoqi.rabbitmq.utils.RabbitConstant;
import com.itlaoqi.rabbitmq.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;


public class WeatherBureau {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection =  RabbitUtils.getConnection();
        Map<String,String> areas = new LinkedHashMap<String,String>();
        areas.put("china.hebei.shijianzhuang.20991011","中国河北石家庄20991011天气");
        areas.put("china.shandong.qingdao.20991011","中国山东青岛20991011天气");
        areas.put("china.henna.zhengzhou.20991011","中国河南郑州20991011天气");
        areas.put("us.cal.la.20991011","美国加州洛杉矶20991011天气");

        areas.put("china.hebei.shijianzhuang.20991012","中国河北石家庄20991012天气");
        areas.put("china.shandong.qingdao.20991012","中国山东青岛20991012天气");
        areas.put("china.henna.zhengzhou.20991012","中国河南郑州20991012天气");
        areas.put("us.cal.la.20991012","美国加州洛杉矶20991012天气");

        Channel channel = connection.createChannel();
        //开启监听
        channel.confirmSelect();
        channel.addReturnListener(new ReturnCallback() {
            @Override
            public void handle(Return r) {
                System.out.println("=================================");
                System.err.println("错误代码:" + r.getReplyCode() + "-错误描述:" + r.getReplyText());
                System.err.println("交换机:" + r.getExchange() + "-路由Key:" + r.getRoutingKey());
                System.err.println("消息主题:" + new String(r.getBody()));

                System.out.println("=================================");
            }
        });
        channel.addConfirmListener(new ConfirmListener() {
            //第二个参数为接受的数据是否为批量接受
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("消息已被broke接受,tag::" + deliveryTag);
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("消息已被broke拒收,tag::" + deliveryTag);
            }
        });
        for (Map.Entry<String,String> area: areas.entrySet()) {
            channel.basicPublish(RabbitConstant.EXCHANGE_WEATHER_TOPIC,area.getKey(),true,null,area.getValue().getBytes());
        }
//        channel.close();
//        connection.close();
    }
}
